package servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import utils.AliOssUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

//上传文件
@WebServlet("/UploadServlet")
@MultipartConfig
public class UploadServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        Map<String, String> result = new HashMap<>();

        try {
            AliOssUtil aliOssUtil = new AliOssUtil();
            Part filePart = request.getPart("file");

            if (filePart != null) {
                String originalFilename = getFileName(filePart);
                String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
                String objectName = UUID.randomUUID() + extension;

                byte[] fileBytes = filePart.getInputStream().readAllBytes();
                String filePath = aliOssUtil.upload(fileBytes, objectName);


                if (filePath != null) {
                    result.put("status", "success");
                    result.put("filePath", filePath);
                } else {
                    result.put("status", "error");
                    result.put("message", "文件路径为空");
                }
            } else {
                result.put("status", "error");
                result.put("message", "未选择文件");
            }
        } catch (Exception e) {
            result.put("status", "error");
            result.put("message", "文件上传失败：" + e.getMessage());
        }

        ObjectMapper mapper = new ObjectMapper();
        String jsonResponse = mapper.writeValueAsString(result);


        response.getWriter().write(jsonResponse);
    }

    private String getFileName(Part part) {
        for (String content : part.getHeader("content-disposition").split(";")) {
            if (content.trim().startsWith("filename")) {
                return content.substring(content.indexOf("=") + 1).trim().replace("\"", "");
            }
        }
        return null;
    }
}
